#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>


int main()
{
  pid_t id = fork();
  if(id<0){
    perror("fork error!\n");
    return 1;
  }
  else if(id == 0){
    //child
    int count = 0;
    while(count < 2){
      printf("child [%d] is running ...\n", getpid());
      sleep(3);
      count++;
    }
    exit(123);
  }
  else{
    //father
    // **********************
    //  进程 的 阻塞式 等待
    // **********************
    //printf("father wait before!\n");
    //int st = 0;
    //pid_t ret = waitpid(-1, &st, 0); //阻塞式等待
    //printf("this is wait test\n");
    //if(WIFEXITED(st) && ret == id){
    //  printf("wait success, child return code id :%d.\n",WEXITSTATUS(st));
    //}
    //else{
    //  printf("wait child failed, return .\n");
    //  return 1;
    //}
   
    // **********************
    //  进程 的 非阻塞式 等待
    // **********************
    int st = 0;
    pid_t ret = 0;
    //printf("father wait before!\n");
    do{
      pid_t ret = waitpid(-1, &st, WNOHANG); //非阻塞式等待
      //printf("this is wait test\n");
      if(ret == 0){
        printf("child is running\n");
      }
      sleep(1);
    }while(ret == 0);
    
    if(WIFEXITED(st) && ret == id){
      printf("wait success, child return code id :%d.\n",WEXITSTATUS(st));
    }
    else{
      printf("wait child failed, return .\n");
      return 1;
    }
    // if(ret>0){
   //  // printf("wait success!\n");
   //  // printf("st ； %d\n ", st);
   //  // printf("child signal :%d\n",st & 0x7F);//111 1111
   //  // printf("child exit code: %d\n",(st>>8)&0xff);
   //   if(st & 0x7F){
   //     printf("child run error!\n");
   //   }
   //   else{
   //     int code = ((st>>8)&0xff);

   //     if(code){
   //       printf("child run success,but result is note right!；code : %d\n",code);
   //     }
   //     else{
   //       printf("child run success ,result is right! :code :%d\n",code);
   //     }
   //   }
   // }
   // else{
   //   printf("wait failed!\n");
   // }
   // printf("father wait after!\n");
  }
  return 0;
}
